import map from "lodash/map";
import difference from "lodash/difference";
import cloneDeep from "lodash/cloneDeep";
import { notification } from "../shared/message";
import ChatRobot from "../shared/wework/chat";

const robotid = "7543cdd5-f746-4136-b73d-102f956598f2";
const robot = new ChatRobot(robotid);

export const statsLabelObj = {
  "2": "角球",
  "3": "黄牌",
  "4": "红牌",
  "8": "点球",
  "21": "射正",
  "22": "射偏"
};
export const incidentsLabelObj = {
  "1": "进球",
  "8": "点球", // 也是进球
  "3": "黄牌",
  "15": "红牌",
  "11": "未知"
};

// 上一次表格数据
let cacheTableData = [];

// 每个区域缓存的数据
const cachePanelStatus = {
  firstPanel: [],
  secondPanel: [],
  thirdPanel: [],
  fourPanel: []
};
// 升降区域的数据id
let diffPanelIds = [];
let cache_diffPanelIds = [];
let cacheDiffTime = Date.now();
// 总条件：如果满足1和3的条件，两个地方的数据都要（重复显示）
// 满足2和3的，也都显示（重复）
// 各区域，只要10分钟进两球都会有标红和声音提示，可选择开关

// 某方总射门（射正比+射偏）>=10 次 && 射正比>=3 && 总射门比>=3 && 比分相加>0
// 有声音提示，可关闭打开
function firstPanel(data) {
  diffPanelIds = []; // 清空上次的数据
  const ids = [];
  const arr = [];
  data.forEach(v => {
    const item = cloneDeep(v);
    const {
      homeFront,
      homeTotal,
      awayFront,
      score,
      awayTotal,
      homeScore,
      awayScore,
      totalScore,
      goal2_in_ten,
      hasGoalIn6074,
      status
    } = item;
    // console.log("goal2_in_ten=", goal2_in_ten);
    if (
      (homeTotal >= 10 || awayTotal >= 10) &&
      shotFrontRateGt3(homeFront, awayFront) &&
      shotRateGt3(homeTotal, awayTotal) &&
      score > "0-0"
    ) {
      item._firstPanel = true;
      item.id = `first_${item.dataId}`;
      ids.push(item.id);
      arr.push(item);
    } else if (process.client && goal2_in_ten) {
      if (window.tenMins2GoalPut1Checked) {
        // 10分钟进2球放①区
        item._firstPanel = true;
        item.id = `first_${item.dataId}`;
        ids.push(item.id);
        arr.push(item);
      }
    }
    if (process.client && window.oneChecked) {
      if (awayScore && homeScore && totalScore >= 3 && hasGoalIn6074) {
        item._firstPanel = true;
        item.id = `first_${item.dataId}`;
        ids.push(item.id);
        arr.push(item);
        if (status.indexOf("75") !== -1) {
          // 发送信息
          sendMdMsg(
            item,
            item.belong == 1 ? item.homeTeam : item.guestTeam,
            "双方都进球，总>=3，且60~74分钟有进球，第75分钟发信息",
            "买大于"
          );
        }
      }
    }
  });
  // 处理升降区域
  const diff = difference(ids, cachePanelStatus.firstPanel);
  cachePanelStatus.firstPanel = [...ids];
  diffPanelIds.push(...diff);

  return sortHandler(arr);
}

// 比分0:0 & 射正比>=3 & 总射门比>=3 & 比分相加===0 || 上半场没进球，下半场进球的
// 有声音提示，可关闭打开
function secondPanel(data) {
  const ids = [];
  const arr = [];
  data.forEach(d => {
    const item = cloneDeep(d);
    const {
      homeFront,
      homeTotal,
      awayFront,
      score,
      awayTotal,
      homeScore,
      awayScore,
      totalScore,
      halfGoalis45, // 半场结束时进球4~5个
      nextHalfGoal2, // 下半场再进2个
      status,
      frontHalfGameNoGoal // 前45分钟无比赛
    } = item;
    if (
      (score == "0-0" &&
        shotFrontRateGt3(homeFront, awayFront) &&
        shotRateGt3(homeTotal, awayTotal)) ||
      frontHalfGameNoGoal
    ) {
      item._secondPanel = true;
      item.id = `second_${item.dataId}`;
      ids.push(item.id);
      arr.push(item);
    }
    if (process.client && window.twoChecked) {
      if (awayScore && homeScore && halfGoalis45) {
        item._secondPanel = true;
        item.id = `second_${item.dataId}`;
        ids.push(item.id);
        arr.push(item);
        if (status.indexOf("45") !== -1 || status.indexOf("中") !== -1) {
          // 发送信息
          sendMdMsg(
            item,
            item.belong == 1 ? item.homeTeam : item.guestTeam,
            "半场结束，双方进球且进球数在 4~5 之间，中场发信息",
            "中场买小于"
          );
        } else {
          // 下半场进多2球
          if (nextHalfGoal2) {
            // 发送信息
            sendMdMsg(
              item,
              item.belong == 1 ? item.homeTeam : item.guestTeam,
              "半场结束，双方进球且进球数在 4~5 之间，下半场再进球2",
              "剧本立马买大于"
            );
          }
        }
      }
    }
  });
  // 处理升降区域
  const diff = difference(ids, cachePanelStatus.secondPanel);
  cachePanelStatus.secondPanel = [...ids];
  diffPanelIds.push(...diff);
  return sortHandler(arr);
}

// 比赛时间>75mins，asc排序
function thirdPanel(data) {
  const ids = [];
  const arr = [];
  data.forEach(item => {
    const newItem = cloneDeep(item);
    const status =
      newItem.status === "中"
        ? "50"
        : newItem.status.replace("'", "").replace("+", "");
    if (Number(status) >= 75) {
      // TODO:中场的情况
      newItem._thirdPanel = true;
      newItem.id = `third_${newItem.dataId}`;
      ids.push(newItem.id);
      arr.push(newItem);
    }
  });
  // 处理升降区域
  cachePanelStatus.thirdPanel = [...ids];
  // const diff = difference(ids, cachePanelStatus.thirdPanel);
  // diffPanelIds.push(...diff); // 去掉第三区域的升降提示
  // 排序
  const sortArr = arr.sort((a, b) => {
    if (a.status < b.status) {
      return -1;
    }
    if (a.status > b.status) {
      return 1;
    }
    return 0;
  });
  // 加上序号
  // sortArr.forEach((item, index) => (item.index = index + 1));
  return sortArr;
}

/**
 * 剩下的比赛，按比分score降序 desc
 * @param {*} data
 * @param {*} dataIds 1，2，3区的dataId数组，用来排除剩余比赛
 */
function fourPanel(data, dataIds) {
  const ids = [];
  const arr = [];
  // 排序
  data.forEach(item => {
    if (!dataIds.includes(item.dataId)) {
      const newItem = cloneDeep(item);
      newItem._fourPanel = true;
      newItem.id = `four_${newItem.dataId}`;
      ids.push(newItem.id);
      arr.push(newItem);
    }
  });
  // 处理升降区域
  // cachePanelStatus.fourPanel = [...ids];

  return sortHandler(arr);
}

// 排序，净胜球多的靠前，净胜球一样，进球总数多的靠前; 然后总射门靠前（可自定义）
function sortHandler(arr) {
  const sortArr = arr.sort((a, b) => {
    const ascore = a.earnScore || 0;
    const bscore = b.earnScore || 0;
    if (a.totalScore && b.totalScore) {
      if (ascore === bscore) {
        // 勾选射门比排序
        if (
          process.client &&
          window.goalRateChecked &&
          a.totalScore === b.totalScore
        ) {
          if (a.earnTotalShot === b.earnTotalShot) {
            return a.totalShot < b.totalShot ? 1 : -1;
          } else {
            return a.earnTotalShot < b.earnTotalShot ? 1 : -1;
          }
        }
        return a.totalScore < b.totalScore ? 1 : -1;
      } else {
        return ascore < bscore ? 1 : -1;
      }
    } else {
      return ascore < bscore ? -1 : 1;
    }
  });
  return sortArr;
}
/**
 * 射正比 >=3
 */
function shotFrontRateGt3(homeFront = 0, awayFront = 0) {
  if (homeFront > 0) {
    if (awayFront > 0) {
      return homeFront / awayFront >= 3 || homeFront / awayFront <= 1 / 3;
    } else {
      // awayFront=0 的情况
      return homeFront >= 3;
    }
  } else {
    // homeFront=0 的情况
    if (awayFront > 0) {
      return awayFront >= 3;
    }
    return false;
  }
}

/**
 * 总射门比 >=3
 */
function shotRateGt3(homeTotal = 0, awayTotal = 0) {
  if (homeTotal > 0) {
    if (awayTotal > 0) {
      return homeTotal / awayTotal >= 3 || homeTotal / awayTotal <= 1 / 3;
    } else {
      // awayTotal=0 的情况
      return homeTotal >= 3;
    }
  } else {
    // homeTotal=0 的情况
    if (awayTotal > 0) {
      return awayTotal >= 3;
    }
    return false;
  }
}

/**
 * 射门数
 * @param {Array<object>} stats
 */
function handleShotCount({ stats = [], score = "0-0" }) {
  if (!Array.isArray(stats)) return;
  const homeCount = [0, 0, 0]; // 主队[射正，射偏，总数]
  const awayCount = [0, 0, 0]; // 客队[射正，射偏，总数]
  stats.forEach(item => {
    if (item.type == 21) {
      homeCount[0] += item.home; //主队射正
      awayCount[0] += item.away; //客队射正
    } else if (item.type == 22) {
      homeCount[1] += item.home; //主队射偏
      awayCount[1] += item.away; //客队射偏
    }
  });
  homeCount[2] = homeCount[0] + homeCount[1];
  awayCount[2] = awayCount[0] + awayCount[1];

  const [homeFront, homeNotFront, homeTotal] = homeCount;
  const [awayFront, awayNotFront, awayTotal] = awayCount;
  const scoreArr = score.split("-");
  const home_score = scoreArr[0];
  const away_score = scoreArr[1];
  const earnScore = home_score - away_score; // 净胜球
  const earnTotalShot = homeTotal - awayTotal; // 总射门比净球

  return {
    homeFront,
    homeNotFront,
    homeTotal,
    awayFront,
    awayNotFront,
    awayTotal,
    homeScore: home_score,
    awayScore: away_score,
    totalScore: home_score + away_score,
    totalShot: homeTotal + awayTotal,
    earnScore: Math.abs(isNaN(earnScore) ? 0 : earnScore),
    earnTotalShot: Math.abs(isNaN(earnTotalShot) ? 0 : earnTotalShot),
    shotRate: `${homeTotal}:${awayTotal}`, // 总射门比
    frontShotRate: `${homeFront}:${awayFront}` // 射正比
  };
}
// 进球
function isGoal(type) {
  return type == 1 || type == 8;
}
/**
 * 进球事件
 */
function goalIncidents(game) {
  const { incidents = [], dataId } = game;
  if (!Array.isArray(incidents)) return;
  const length = incidents.length;
  let last_goal_second = 0; // 上一次进球事件 秒为单位
  const goalGridData = [];
  const nextHalfArr = [];
  const half45Arr = [];
  incidents.forEach(item => {
    if (isGoal(item.type) && item.time) {
      if (item.time > 45) {
        nextHalfArr.push(item);
      } else {
        half45Arr.push(item);
      }
    }
  });
  console.log(
    `${game.homeTeam}vs${game.guestTeam}:前，后=`,
    half45Arr.length,
    nextHalfArr.length
  );
  incidents.forEach((item, index) => {
    // 进球type=1
    if (isGoal(item.type) && item.second) {
      game.last_goal_second = last_goal_second;
      // 在同一个半场（排除休息时间也算进去了）
      const inSameHalfGame =
        (item.time <= 45 && last_goal_second / 60 < 45) ||
        (item.time > 45 && last_goal_second / 60 > 45);
      // 10分钟进两球
      item.goal2_between_tenmins =
        Math.ceil((item.second - last_goal_second) / 60) <= 10 &&
        last_goal_second !== 0 &&
        inSameHalfGame;
      game.goal2_between_11mins =
        Math.ceil((item.second - last_goal_second) / 60) <= 11 &&
        last_goal_second !== 0 &&
        inSameHalfGame;
      game.nextHalfGoal2InTenminus4570 =
        Math.ceil((item.second - last_goal_second) / 60) <= 10 &&
        last_goal_second > 45 * 60 &&
        item.second <= 70 * 60;
      game.nextHalfGoal2InTenminus4575 =
        Math.ceil((item.second - last_goal_second) / 60) <= 10 &&
        last_goal_second > 45 * 60 &&
        item.second <= 75 * 60;
      last_goal_second = item.second;
      item.dataId = dataId;
      if (!game.first_goal_second) {
        game.first_goal_second = item.second;
        // 45分钟前没有进过球：true
        game.frontHalfGameNoGoal = game.first_goal_second > 45 * 60;
      }
    }
    if (item.goal2_between_tenmins) {
      // 标识10分钟进过2球的数据
      game.goal2_in_ten = true;
    }
    if (isGoal(item.type)) {
      if (item.time >= 60 && item.time <= 74) {
        game.hasGoalIn6074 = true;
      }
      if (item.time <= 45) {
        // 上半场是否有进球标识
        if (item.belong === 1) {
          game.homeTeamHalfScore = true;
        } else {
          game.guestTeamHalfScore = true;
        }
      }
      goalGridData.push({
        goalTeam: item.belong === 1 ? game.homeTeam : game.guestTeam,
        goalMan: item.player_name,
        goalTime: item.time
      });
    }
    // 最新进球数据 & 声音开关打开
    if (process.client) {
      if (isGoal(item.type) && item.time && index === length - 1) {
        if (half45Arr.length >= 4 && half45Arr.length <= 5) {
          game.halfGoalis45 = true;
        } else {
          game.halfGoalis45 = false;
        }
        console.log("halfGoalis45=", game.halfGoalis45, half45Arr.length);
        if (half45Arr.length < 2) {
          game.halfGoalLess2 = true;
        }
        if (nextHalfArr.length === 2) {
          game.nextHalfGoal2 = true;
        } else {
          game.nextHalfGoal2 = false;
        }
        game.last_goal_time = item.time;

        if (item.time >= 70) {
          const arr0 = [];
          const arr1 = [];
          goalGridData.forEach(g => {
            if (g.belong === 1) {
              arr1.push(g);
            } else {
              arr0.push(g);
            }
          });
          game.singleTeamScoreIn70 = !(arr0.length && arr1.length);
        }
        const storage = window.sessionStorage.getItem(
          `goal_${dataId}_${item.second}`
        );

        if (game.status !== "-" && game.status !== "完") {
          let time = "";
          if (game.status === "中") {
            time = 45;
          } else {
            time = game.status.replace("'", "").replace("+", "");
          }
          if (Number(time) - 1 > item.time) {
            // 2分钟后了，停止动画
            game.toggleAnimate = -1;
          } else if (time === item.time) {
            game.toggleAnimate = item.belong;
          }
        }

        const wework1 = window.localStorage.getItem(
          `wework1_${dataId}_${item.second}`
        );
        const wework2 = window.localStorage.getItem(
          `wework2_${dataId}_${item.second}`
        );
        const wework3 = window.localStorage.getItem(
          `wework3_${dataId}_${item.second}`
        );

        // 0-36分钟，11分钟进2
        if (window.weworkChecked) {
          if (game.goal2_between_11mins && item.item <= 36 && !wework1) {
            sendMdMsg(
              game,
              item.belong == 1 ? game.homeTeam : game.guestTeam,
              "0-36分钟，11分钟进2",
              "立马买大于"
            );
            window.localStorage.setItem(
              `wework1_${dataId}_${item.second}`,
              true
            );
          }

          // 45~75分钟，10分钟进2，，且双方射门总和1~20之间。
          // （触发条件就发，不好控制第79分钟发送信息）
          if (
            /* ((game.homeScore === 0 && game.awayScore > 0) ||
              (game.awayScore === 0 && game.homeScore > 0)) && */
            game.totalShot <= 20 &&
            game.nextHalfGoal2InTenminus4575 &&
            singleTeamScoreIn70 &&
            !wework2
          ) {
            sendMdMsg(
              game,
              item.belong == 1 ? game.homeTeam : game.guestTeam,
              "45~75分钟，10分钟进2，0~70单方进球，且双方射门中总和1~20之间",
              "买小于"
            );
            window.localStorage.setItem(
              `wework2_${dataId}_${item.second}`,
              true
            );
          }
          // 45~70分钟，10分钟进2，0~70双方进球，且上半场进球<=2
          if (
            halfGoalLess2 &&
            game.nextHalfGoal2InTenminus4570 &&
            !singleTeamScoreIn70 &&
            !wework3
          ) {
            sendMdMsg(
              game,
              item.belong == 1 ? game.homeTeam : game.guestTeam,
              "45~70分钟，10分钟进2，0~70双方进球，且上半场进球<=2",
              "剧本立马买大于"
            );
            window.localStorage.setItem(
              `wework3_${dataId}_${item.second}`,
              true
            );
          }
        }

        // 进球播放一次声音（可能满足10分钟2球）
        if (!storage) {
          // 播放声音
          if (window.tenMinusAudioChecked && item.goal2_between_tenmins) {
            playAudio(3);
          }
          if (window.goalAudioChecked) {
            playAudio(2);
          }

          /*   notification(
            `${
              item.belong == 1 ? game.homeTeam : game.guestTeam
            }进球啦!!！现比分：${game.score}`,
            item.goal2_between_tenmins ? 20000 : 5000
          ); */
          notification(
            item.belong == 1,
            item.belong == 1 ? game.homeTeam : game.guestTeam,
            game.score,
            game.last_goal_time
          );
          // 表示播放过声音了，标记一下
          window.sessionStorage.setItem(
            `goal_${dataId}_${item.second}`,
            "alert"
          );
        }
      }
      // 循环到最后一个事件
      if (
        process.client &&
        window.weworkChecked &&
        item.time &&
        index === length - 1
      ) {
        const wework4 = window.localStorage.getItem(
          `wework4_${dataId}_${item.second}`
        );
        // 42分钟之前红牌
        if (item.type === 15 && !wework4 && item.time <= 42) {
          sendMdMsg(
            game,
            item.belong == 1 ? game.homeTeam : game.guestTeam,
            "42分钟之前红牌",
            "买大于"
          );
          window.localStorage.setItem(`wework4_${dataId}_${item.second}`, true);
        }
      }
    }
  });

  game.goalGridData = goalGridData;
}

function getItemByDataId(data = [], dataId) {
  return data.filter(d => (d.dataId = dataId))[0] || {};
}

function playAudio(type) {
  if (process.client) {
    if (Array.isArray(type)) {
      type.forEach(t => window.playAudio(t));
    } else if (typeof type === "number") {
      window.playAudio(type);
    }
  }
}

export function handleLivesData(livesData) {
  return livesData.map(game => {
    const shotObj = handleShotCount(game);
    Object.assign(game, shotObj);
    goalIncidents(game);
    if (!game.status === "-" || !game.status) {
      game.status = getItemByDataId(cacheTableData, game.dataId).status;
    }
    // 移除避免不必要的性能监听
    delete game.incidents;
    delete game.stats;

    return game;
  });
}

/**
 * 根据规则做分区域展示和排序
 * @param {*} data
 */
export function sortAndRenderByRules(data) {
  const first = firstPanel(data);
  const second = secondPanel(data);
  const third = thirdPanel(data);
  if (first.length > 0) {
    first.unshift({
      _panel: "true",
      title: "第①区域",
      panelTip: "某方总射门数>=10 次 & 射正比>=3 & 总射门比>=3 & 比分相加>0"
    });
  }
  if (second.length > 0) {
    second.unshift({
      _panel: "true",
      title: "第②区域",
      panelTip: "比分0:0 & 射正比>=3 & 总射门比>=3"
    });
  }
  if (third.length > 0) {
    third.unshift({
      _panel: "true",
      title: "第③区域",
      panelTip: "比赛时间>=75分钟，升序排序"
    });
  }

  const someArr = [...first, ...second, ...third];
  const dataIds = map(someArr, "dataId");
  const four = fourPanel(data, dataIds);
  if (four.length > 0) {
    four.unshift({
      _panel: "true",
      title: "第④区域",
      panelTip: "①、②、③之外的比赛，按比分降序"
    });
  }
  const newData = someArr.concat(four);
  let markTopList = [];
  // 升降区域数据变化播放提示音
  if (process.client) {
    if (diffPanelIds.length > 0 && window.panelAudioChecked) {
      playAudio(1);
    }
    let markedList = window.sessionStorage.getItem("markedList") || "[]";
    markedList = JSON.parse(markedList);

    if (markedList.length > 0) {
      newData.forEach(item => {
        if (markedList.includes(item.id)) {
          item.marked = true;
          const newItem = cloneDeep(item);
          newItem.index = "top";
          markTopList.push(newItem);
        }
      });
    }
  }
  if (markTopList.length > 0) {
    markTopList.unshift({
      _panel: "true",
      title: "置顶",
      panelTip: "点击收藏置顶的比赛"
    });
  }
  cacheTableData = newData;
  // 生成序号
  let count = 1;
  newData.forEach(item => {
    if (!item._panel) {
      item.index = count;
      count += 1;
    }
  });
  // 缓存延长高亮时间
  if (Date.now() - cacheDiffTime < 25 * 1000 && diffPanelIds.length === 0) {
    diffPanelIds = [...cache_diffPanelIds];
  } else {
    cache_diffPanelIds = [...diffPanelIds];
  }

  return [markTopList.concat(newData), diffPanelIds];
}

function sendMdMsg(game, teamName, text1, text2) {
  const { eventName, guestTeam, homeTeam } = game;
  const msg = `【${eventName}】比赛进球了\n  >赛事: <font color="comment">${homeTeam} vs ${guestTeam}</font> \n  >进球方: <font color="info">${teamName}</font> \n  >条件:  <font color="comment">${text1}</font> \n  >建议操作:  <font color="info">${text2}</font>`;
  robot.sendMdMsg(msg, ["18577912580"]);
}
